#include "Game.h"

#include <map>
#include <algorithm>

enum DealerContext
{
	DealerHit = 1,
	DealerStay
};

void Game::GameLoop()
{
	for(int x = 0; x < PlayerCount; ++x)
	{
		currentPlayer = playerList[x];
		if(!(currentPlayer->IsFat || currentPlayer->IsStaying))
		{
			CurrentTurn();
			PressKeyToContinue();
		}
	}
}

void Game::CurrentTurn()
{
	context->RoundContext(currentRound);
	PrintHand(currentPlayer);

	if(currentPlayer->PlayerControlled)
	{
		context->ActionContext(Input());
	}
	else
	{
		HandValue(currentPlayer->Hand) > 17 ? context->ActionContext(DealerStay) : context->ActionContext(DealerHit);
	}
}

//For sorting players to help determine leader
#pragma region Sort utility
struct sort_map
{
	int key;
	Player* val;
};

bool SortPred(sort_map& a, sort_map& b)
{
	return a.key > b.key;
}
#pragma endregion

void Game::DetermineLeader()
{
	std::map<int, Player*> tmpMap;
	std::map<int, Player*>::iterator it;
	std::vector<sort_map> tmpVec;
	sort_map sortie;

	for(unsigned int x = 0; x < playerList.size(); ++x)
	{
		if(playerList[x]->IsFat == false)
		{
			tmpMap.insert(std::pair<int, Player*>(HandValue(playerList[x]->Hand), playerList[x]));
		}
	}

	if(tmpMap.empty())
	{
		currentLeader = NULL;
		return;
	}

	for(it = tmpMap.begin(); it != tmpMap.end(); ++it)
	{
		sortie.key = it->first; sortie.val = it->second;
		tmpVec.push_back(sortie);
	}

	if(tmpVec.size() == 1)
	{
		currentLeader = tmpVec[0].val;
		return;
	}

	std::sort(tmpVec.begin(), tmpVec.end(), SortPred);

	if(currentLeader == NULL || currentLeader != tmpVec[0].val)
		currentLeader = tmpVec[0].val;
}

void Game::CheckForEndgame()
{
	int inPlay = 0;
	for(unsigned int x = 0; x < PlayerCount; ++x)
	{
		if(!(playerList[x]->IsFat || playerList[x]->IsStaying))
			++inPlay;
	}

	if(inPlay < 1)
		Endgame = true;
	else
		++currentRound;
}